import { fetchEventSource } from '@microsoft/fetch-event-source';
import { getToken } from '@/utils/auth';

export default function fetchSSE(url, options = {}) {
  let source;
  let ctrl;
  const isPost = options.method?.toUpperCase() === 'POST';
  // post请求使用fetchEventSource, get请求使用原生EventSource
  if (isPost) {
    ctrl = new AbortController();
    source = fetchEventSource(url, {
      ...options,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `${getToken()}`,
        ...(options.headers || {})
      },
      body: JSON.stringify(options.body || {}),
      signal: ctrl.signal,
      openWhenHidden: true // 确保即使页面不在前台也能接收到服务器的更新
    });
  } else {
    source = new EventSource(url);
    source.onopen = (event) => {
      options.onopen(event);
    };
    source.onmessage = (event) => {
      options.onmessage(event);
    };
    source.onerror = (event) => {
      options.onerror(event);
    };
  }

  return {
    close() {
      if (isPost) {
        ctrl.abort();
      } else {
        source.close();
      }
    }
  };
}
